{% extends "base.html" %}

{% block head %}
    <style>
        :root {
            --primary-color: #1976d2;
            --primary-hover: #1565c0;
            --border-color: #e0e0e0;
            --light-gray: #f5f5f5;
            --text-color: #333;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }

        body {
            color: var(--text-color);
            background-color: #f8f9fa;
        }

        .ConfigureSearchParameters_details {

        }

        .content-section {
            display: none;
            width: 1000px;
            margin: 0 auto;
        }

        .content-section.active {
            display: block;
        }

        a {
            text-decoration: none;
            color: inherit;
            cursor: inherit;
        }

        .search-highlight {
            background-color: yellow;
        }

         #search-container {
            position: fixed;
            top: 180px;
            right: -250px; /* 初始隐藏状态 */
            width: 240px;
            background: white;
            padding: 10px;
            border: 1px solid #ccc;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            transition: right 0.3s ease; /* 添加平滑过渡 */
            z-index: 1000;
        }

        #search-container.visible {
            right: 10px; /* 显示状态 */
        }

        #search-toggle {
            position: fixed;
            top: 180px;
            right: 10px;
            width: 30px;
            height: 30px;
            background: white;
            border: 1px solid #ccc;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 999;
            transition: right 0.3s ease;
        }

        #search-container.visible + #search-toggle {
            right: 260px; /* 搜索框显示时，按钮向右移动 */
        }

    </style>
{% endblock %}

{% block content %}

    <!-- 搜索控件 -->
    <div id="search-container">
        <input type="text" id="search-input" placeholder="输入搜索词...">
        <button onclick="search()">搜索</button>
        <button onclick="clearSearch()">清除</button>
        <div>
            <button onclick="prevMatch()">上一个</button>
            <button onclick="nextMatch()">下一个</button>
            <span id="search-status">0/0</span>
        </div>
    </div>

    <div id="search-toggle">🔍</div>

    <div class="ConfigureSearchParameters_details" id="content">

        <!-- 根据ID值显示不同内容 -->
        <div id="section1" class="content-section">
            {% include "pages/UpperMenuPage/zdwj_1.html" %}
        </div>

        <div id="section2" class="content-section">
            {% include "pages/UpperMenuPage/zdwj_2.html" %}
        </div>

        <div id="section3" class="content-section">
            {% include "pages/UpperMenuPage/zdwj_3.html" %}
        </div>

        <div id="section4" class="content-section">
            {% include "pages/UpperMenuPage/zdwj_4.html" %}
        </div>

        <div id="section5" class="content-section">
            {% include "pages/UpperMenuPage/zdwj_5.html" %}
        </div>

        <div id="section6" class="content-section">
            {% include "pages/UpperMenuPage/zdwj_6.html" %}
        </div>

        <div id="defaultSection" class="content-section">
            <h2 class="section-title">这是当ID不匹配任何文件。</h2>
            <p>当前ID值: <span id="displayValue"></span></p>
        </div>
    </div>

{% endblock %}

{% block scripts %}
    <script>
        let currentValue = null; // 存储当前ID值
        let currentIndex = 0;
        let matches = [];
        let searchTerm = '';

        document.addEventListener('DOMContentLoaded', function() {
            // 获取当前URL的查询参数
            const urlParams = new URLSearchParams(window.location.search);
            currentValue = urlParams.get('id');
            console.log('获取到的ID值:', currentValue);

            // 显示获取到的值（用于调试）
            document.getElementById('displayValue').textContent = currentValue || '未提供';

            // 隐藏所有内容部分
            document.querySelectorAll('.content-section').forEach(section => {
                section.classList.remove('active');
            });

            // 根据ID值显示对应的内容部分
            if (currentValue == '1') {
                document.getElementById('section1').classList.add('active');
            } else if (currentValue == '2') {
                document.getElementById('section2').classList.add('active');
            } else if (currentValue == '3') {
                document.getElementById('section3').classList.add('active');
            } else if (currentValue == '4') {
                document.getElementById('section4').classList.add('active');
            } else if (currentValue == '5') {
                document.getElementById('section5').classList.add('active');
            } else if (currentValue == '6') {
                document.getElementById('section6').classList.add('active');
            } else {
                // 如果没有匹配的ID或ID为空，显示默认部分
                document.getElementById('defaultSection').classList.add('active');

                // 可以在这里添加对无效ID的处理逻辑
                if (currentValue !== null) {
                    console.warn('未知的ID值:', currentValue);
                }
            }

            // 初始化搜索框状态隐藏
            const searchContainer = document.getElementById('search-container');
            const searchToggle = document.getElementById('search-toggle');
            let isSearchVisible = false;

            // 从本地存储读取搜索框状态
            const savedState = localStorage.getItem('searchPanelVisible');
            if (savedState === 'true') {
                searchContainer.classList.add('visible');
                isSearchVisible = true;
                updateTogglePosition();
            }

            // 切换按钮点击事件
            searchToggle.addEventListener('click', toggleSearchPanel);

            // Ctrl+F 快捷键监听
            document.addEventListener('keydown', function(e) {
                // 阻止默认的浏览器搜索行为
                if (e.ctrlKey && e.key === 'f') {
                    e.preventDefault();
                    toggleSearchPanel();

                    // 聚焦到搜索输入框
                    if (searchContainer.classList.contains('visible')) {
                        document.getElementById('search-input').focus();
                    }
                }
            });

            function toggleSearchPanel() {
                isSearchVisible = !isSearchVisible;

                if (isSearchVisible) {
                    searchContainer.classList.add('visible');
                } else {
                    searchContainer.classList.remove('visible');
                    // 清除搜索状态当隐藏时
                    clearSearch();
                }

                updateTogglePosition();
                // 保存状态到本地存储
                localStorage.setItem('searchPanelVisible', isSearchVisible);
            }

            function updateTogglePosition() {
                // 这个逻辑现在由CSS自动处理
                // 保留这个函数以便未来扩展
            }

            // 窗口大小调整时确保搜索框不会超出视口
            window.addEventListener('resize', function() {
                if (isSearchVisible) {
                    const containerRect = searchContainer.getBoundingClientRect();
                    if (containerRect.right > window.innerWidth) {
                        searchContainer.style.right = `${window.innerWidth - containerRect.width - 10}px`;
                    }
                }
            });
            // 从选区创建新的临时文件 - 结束
        });

        // 文字搜索
        function search() {
            clearHighlights(); // 清除之前的高亮

            searchTerm = document.getElementById('search-input').value.trim();
            if (!searchTerm) return;

            const activeSection = document.querySelector('.content-section.active');
            if (!activeSection) return;

            matches = [];
            const textNodes = [];

            // 收集所有文本节点（跳过搜索控件内的节点）
            const walker = document.createTreeWalker(
                activeSection,
                NodeFilter.SHOW_TEXT,
                {
                    acceptNode: function(node) {
                        return (node.nodeValue.trim() && !isDescendant(node, document.getElementById('search-container')))
                            ? NodeFilter.FILTER_ACCEPT
                            : NodeFilter.FILTER_REJECT;
                    }
                },
                false
            );

            let node;
            while (node = walker.nextNode()) {
                textNodes.push(node);
            }

            // 查找并高亮所有匹配项
            textNodes.forEach(textNode => {
                const parent = textNode.parentNode;
                let text = textNode.nodeValue;
                const regex = new RegExp(searchTerm, 'gi');
                let lastIndex = 0;
                let match;

                while ((match = regex.exec(text)) !== null) {
                    const matchStart = match.index;
                    const matchEnd = matchStart + match[0].length;

                    // 分割文本节点：前部分
                    const beforeMatch = text.substring(0, matchStart);
                    const matchingText = text.substring(matchStart, matchEnd);
                    const afterMatch = text.substring(matchEnd);

                    // 替换文本节点为"前部分"
                    textNode.nodeValue = beforeMatch;

                    // 创建高亮元素
                    const highlight = document.createElement('span');
                    highlight.className = 'search-highlight';
                    highlight.textContent = matchingText;

                    // 插入高亮元素
                    parent.insertBefore(highlight, textNode.nextSibling);

                    // 如果有剩余文本，创建新的文本节点
                    if (afterMatch) {
                        const remainingText = document.createTextNode(afterMatch);
                        parent.insertBefore(remainingText, highlight.nextSibling);
                        textNode = remainingText; // 继续处理剩余文本
                    } else {
                        textNode = null; // 无剩余文本
                    }

                    // 保存高亮元素用于导航
                    matches.push(highlight);

                    // 更新文本和正则位置
                    text = afterMatch;
                    regex.lastIndex = 0;

                    // 如果没有更多文本，退出循环
                    if (!text) break;
                }
            });

            currentIndex = 0;
            updateStatus();

            if (matches.length > 0) {
                scrollToMatch(0);
            }
        }

        function clearHighlights() {
            document.querySelectorAll('.search-highlight').forEach(el => {
                const parent = el.parentNode;
                parent.replaceChild(document.createTextNode(el.textContent), el);
                parent.normalize(); // 合并相邻的文本节点
            });
            matches = [];
            updateStatus();
        }

        function clearSearch() {
            document.getElementById('search-input').value = '';
            clearHighlights();
        }

        function prevMatch() {
            if (matches.length === 0) return;
            currentIndex = (currentIndex - 1 + matches.length) % matches.length;
            scrollToMatch(currentIndex);
        }

        function nextMatch() {
            if (matches.length === 0) return;
            currentIndex = (currentIndex + 1) % matches.length;
            scrollToMatch(currentIndex);
        }

        function scrollToMatch(index) {
            matches[index].scrollIntoView({ behavior: 'smooth', block: 'center' });

            // 临时改变高亮颜色以区分当前选中项
            matches.forEach((match, i) => {
                match.style.backgroundColor = i === index ? 'orange' : 'yellow';
            });

            updateStatus();
        }

        function updateStatus() {
            document.getElementById('search-status').textContent =
                matches.length > 0 ? `${currentIndex + 1}/${matches.length}` : '0/0';
        }

        function isDescendant(child, parent) {
            let node = child.parentNode;
            while (node !== null) {
                if (node === parent) return true;
                node = node.parentNode;
            }
            return false;
        }

        // 添加键盘快捷键支持（可选）
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'f') {
                e.preventDefault();
                document.getElementById('search-input').focus();
            }
        });
    </script>
{% endblock %}